#!/usr/bin/python
# -*- coding: utf-8 -*-


from twisted.internet import reactor
from twisted.internet.serialport import SerialPort
from twisted.internet.protocol import Protocol, Factory
from twisted.protocols.basic import LineReceiver


import threading


class ArduinoLog(LineReceiver):
    def __init__(self):
        self.received=[]
        self._row=""

    def connectionMade(self):
        print "Connected from"#, self.transport.client
        #self.transport.write('<hits>')
    def dataReceived(self, data):
        if data=="\n":
            print self._row
            self.received.append(self._row)
            self.transport.write(self._row)
            self._row=""
        else:
            self._row+=data

    
    def connectionLost(self, reason):
        print "Disconnected from"#, self.transport.client



class arduino_serial:


    def __init__(self,port="/dev/ttyUSB0",baudrate=9600,autostart=True):
        self.port=port
        self.baudrate=baudrate
        self.autostart=autostart
        self.__startSerial__()
        if self.autostart:
            self.thread.start()
        
    
    
    def __initSerialInThread__(self):
        self.serial_class=ArduinoLog()
        self.serial=SerialPort(self.serial_class, self.port, reactor, baudrate=self.baudrate)
        reactor.run(installSignalHandlers=1)
        

    def __startSerial__(self):
        self.thread=threading.Thread(target=self.__initSerialInThread__, args=())
     




if __name__ == "__main__":
    import time
    print "standalone mode on..."
    arduino=arduino_serial()
    c=10
    while c>0:
        time.sleep(1)
        print len(arduino.serial_class.received), "len of serial.received"
        c-=1
else:
    pass
